package com.devin.web.lister;


import com.devin.model.dto.ChatMessage;
import com.devin.model.entity.Room;
import com.devin.model.enums.MessageType;
import com.devin.repository.RoomRepository;
import com.devin.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.socket.messaging.SessionConnectedEvent;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

import java.util.List;
import java.util.Map;
import java.util.Optional;


/**
 * @author: simpl
 * @date: 2020/3/30
 * @time: 14:59
 * @description: 
 */


@CrossOrigin
@Slf4j
@Component
public class WebSocketListener {

    private final RedisUtil redisUtil;

    private final RoomRepository roomRepository;

    private final SimpMessageSendingOperations messagingTemplate;

    @Autowired
    public WebSocketListener(RedisUtil redisUtil, RoomRepository roomRepository, SimpMessageSendingOperations messagingTemplate) {
        this.redisUtil = redisUtil;
        this.roomRepository = roomRepository;
        this.messagingTemplate = messagingTemplate;
    }


    @EventListener
    public void handleWebSocketListener(SessionConnectedEvent event){
        log.info("收到连接");
       /* StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
        String username = (String) headerAccessor.getSessionAttributes().get("username");*/
       /* log.info(username + "   连接");*/
    }


    @EventListener
    public void handleWebSocketDisconnectListener(SessionDisconnectEvent event){
        StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
        Map<String, Object> sessionAttributes = headerAccessor.getSessionAttributes();
        log.info("sessionAttributes:" + sessionAttributes.toString());
        String username = (String) headerAccessor.getSessionAttributes().get("username");
        String roomId = (String) headerAccessor.getSessionAttributes().get("roomId");
        if(!roomId.contains("live")){
            leave(new Long(roomId),username);
        }
        if(username != null) {
            ChatMessage chatMessage = new ChatMessage();
            chatMessage.setType(MessageType.LEAVE.getType());
            chatMessage.setSender(username);
            messagingTemplate.convertAndSend("/topic/"+roomId, chatMessage);
        }
    }
    private boolean leave(Long roomId,String username){
        Optional<Room> byId = roomRepository.findById(roomId);
        //如果不存在 就返回false
        if(!byId.isPresent()){
            return false;
        }
        int currentPeople = byId.get().getCurrentPeople();
        if(currentPeople == 1){
            log.info("删除房间" + roomId);
            roomRepository.deleteById(roomId);
            redisUtil.del(roomId.toString());
        }else{
            //redis 操作
            List<String> userList = (List<String>) redisUtil.get(roomId.toString());
            userList.remove(username);
            redisUtil.set(roomId.toString(),userList);
            log.info("更新房间人数");
            byId.get().setCurrentPeople(currentPeople - 1);
            roomRepository.save(byId.get());
        }
        return true;
    }


}
